<template>
  <el-card v-show="visible" shadow="always" class="aui-card--fill" :visible.sync="visible"
           :title="!dataForm.id ? $t('add') : $t('update')" :close-on-click-modal="false"
           :close-on-press-escape="false" id="overflow" style="position: absolute">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmitHandle()"
             :label-width="$i18n.locale === 'en-US' ? '120px' : '80px'" style="width:80%;">


      <el-row>
        <el-col :span="12">
          <el-form-item label="套餐名称" prop="name">
            <el-input v-model="dataForm.name" placeholder="套餐名称" style="width: 80%"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="套餐分类" prop="categoryId">
            <el-select v-model="dataForm.categoryId" placeholder="请选择套餐分类">
              <el-option v-for="(item,index) in categoryList" :key="item.id" :label="item.name"
                         :value="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="套餐价格" prop="price">
            <el-input v-model="dataForm.price" placeholder="套餐价格" style="width: 80%"></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="编码" prop="code">
            <el-input v-model="dataForm.code" placeholder="编码" style="width: 80%"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="套餐菜品" prop="name">

        <div width="80%">
          <span> <el-button @click="initDish" type="success" icon="el-icon-plus" round>添加菜品</el-button></span>
<!--          <dish-container @hook:updated="initDish" ref="dishList" v-if="dishVisible==true"-->
<!--                          style="display: none"></dish-container>-->

          <div style="padding: 10px" v-if="dataForm.setmealDishes.length!=0">
            <el-table v-loading="dishesLoading" :data="dataForm.setmealDishes" border
                      height="500" padding="80%"
                      @selection-change="dataListSelectionChangeHandle" style="width: 70%;">
              <el-table-column prop="name" label="菜品名称" header-align="center" align="center"
                               width="150"></el-table-column>

              <el-table-column prop="price" label="菜品原价" header-align="center" align="center" width="120">
                <template v-slot:default="{row}">
                  <span>￥{{ (row.price / 100).toFixed(2) }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="copies" label="份数" header-align="center" align="center">
                <template v-slot:default="{row}">
                  <el-input-number v-model="row.copies"  :min="1" :max="10" label="份数"
                                   width="180"></el-input-number>
                </template>
              </el-table-column>
              <el-table-column :label="$t('handle')" header-align="center" align="center" width="120">
                <template slot-scope="scope">
                  <el-button v-if="$hasPermission('demo:setmealdish:delete')" type="text" size="small"
                             @click="deleteSetmealDish(scope.row.dishId)">{{ $t('delete') }}
                  </el-button>
                </template>
              </el-table-column>
            </el-table>

          </div>

        </div>
      </el-form-item>

      <el-form-item label="菜品图片" prop="image">
        <el-upload
            class="avatar-uploader"
            :action="url"
            ref="upload"
            :show-file-list="false"
            :before-upload="beforeUploadHandle"
            :on-success="successHandle"

        >
          <img v-if="imageUrl" :src="imageUrl" class="avatar" v-model="imageUrl">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>

      <el-form-item label="描述信息" prop="description">
        <el-input v-model="dataForm.description" placeholder="描述信息" type="textarea"></el-input>
      </el-form-item>


      <el-form-item :label="$t('updateStatus')" prop="status">
        <el-radio-group v-model="dataForm.status">
          <el-radio :label="1">{{ $t('updateStatusBatch') }}</el-radio>
          <el-radio :label="0">{{ $t('updateStatusBatch_stop') }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item>
        <div class="btn-box">
          <el-button @click="visible = false">{{ $t('cancel') }}</el-button>
          <el-button type="primary" @click="dataFormSubmitHandle()">{{ $t('confirm') }}</el-button>
        </div>
      </el-form-item>
    </el-form>
    <!--   ssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss   -->
    <el-dialog
        :title="$t('add') +'菜品' " :close-on-click-modal="false" :close-on-press-escape="false"
        :visible.sync="dialogVisible" width="70%" append-to-body style="position: absolute">

      <div class="dishBox" >

        <el-row width="100%" :gutter="10">
          <el-col :span="4">
            <div class="dishBox-category" v-if="search==false" >
              <!--    不知为何集合遍历了key变成数组索引，有明白的请联系我下    -->
              <div  :class="[item.active?'dishBox-category-newItem':'dishBox-category-item']" v-for="(item,index) in categoryDish" :key="item.id"
                    @click="findDish(item,index)">{{ item.name }}
              </div>
            </div>
          </el-col>
          <el-col :span="11">
            <div class="dishBox-dish" >
              <el-input v-model="inputValue" size="medium" placeholder="根据菜品名搜索" clearable
                        style="width: 30%;margin-bottom: 10px" @keyup.enter.native="searchDish">
                <i slot="prefix" class="el-input__icon el-icon-search" @click="searchDish"></i></el-input>
                <el-button class="dish-btn" v-if="search==true" @click="backCategory">返回</el-button>
              <el-table  ref="multipleTable" :data="dishTable" border height="500" @selection-change="dishSelectionChangeHandle">
                <el-table-column type="selection" header-align="center" align="center" width="40"></el-table-column>
                <el-table-column prop="name" label="菜品名称" header-align="center" align="center"></el-table-column>

                <el-table-column prop="status" :label="$t('updateStatus')" header-align="center" align="center">
                  <template v-slot:default="{row}">
                    <el-tag type="success" v-if="row.status===1">{{ $t('updateStatusBatch') }}</el-tag>
                    <el-tag type="warning" v-else>{{ $t('updateStatusBatch_stop') }}</el-tag>
                  </template>
                </el-table-column>

                <el-table-column prop="price" label="菜品原价" header-align="center" align="center">
                  <template v-slot:default="{row}">
                    <span>￥{{ (row.price / 100).toFixed(2) }}</span>
                  </template>
                </el-table-column>
              </el-table>

            </div>
          </el-col>
          <el-col :span="9">
            <div class="dishBox-choose">
              <el-tag v-for="(item,i) in dishArray":key="item.id" >
                 <span>{{item.name}}</span><span>{{item.status==1?'在售':'停售'}}
              </span><span>{{item.price}}</span><i @click="deleteDish(i)" class="el-icon-close"></i>
              </el-tag>
            </div>
          </el-col>
        </el-row>


        <!--            <div class="dishBox-category">-->
        <!--              <div class="dishBox-category-item"  v-for="(value,key) in categoryMap" :key="key"-->
        <!--                   ref="changeCty"  :label="value" :value="key"></div>-->
        <!--            </div>-->
        <!--            <div class="dishBox-dish">-->

        <!--              <el-table :data="dishList" border height="250"  style="width: 50%">-->
        <!--                <el-table-column type="selection" header-align="center" align="center" width="40"></el-table-column>-->
        <!--                <el-table-column prop="name" label="菜品名称" header-align="center" align="center" ></el-table-column>-->

        <!--                <el-table-column prop="status" :label="$t('updateStatus')" header-align="center" align="center">-->
        <!--                  <template v-slot:default="{row}">-->
        <!--                    <el-tag type="success" v-if="row.status===1">{{$t('updateStatusBatch')}}</el-tag>-->
        <!--                    <el-tag type="warning" v-else>{{$t('updateStatusBatch_stop')}}</el-tag>-->
        <!--                  </template>-->
        <!--                </el-table-column>-->

        <!--                <el-table-column prop="price" label="菜品原价" header-align="center" align="center" >-->
        <!--                  <template v-slot:default="{row}">-->
        <!--                    <span>￥{{(row.price/100).toFixed(2)}}</span>-->
        <!--                  </template>-->
        <!--                </el-table-column>-->
        <!--              </el-table>-->
        <!--                <el-pagination-->
        <!--                    :current-page="page"-->
        <!--                    :page-sizes="[10, 20, 50, 100]"-->
        <!--                    :page-size="limit"-->
        <!--                    :total="total"-->
        <!--                    layout="total, sizes, prev, pager, next, jumper"-->
        <!--                    @size-change="pageSizeChangeHandle"-->
        <!--                    @current-change="pageCurrentChangeHandle">-->
        <!--                </el-pagination>-->

        <!--            </div>-->
        <!--            <div class="dishBox-choose"></div>-->

      </div>


      <span slot="footer" class="dialog-footer">
           <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="submitDish">确 定</el-button>
        </span>
    </el-dialog>

  </el-card>
</template>

<script>
import debounce from 'lodash/debounce'
import {getCategoryList,getDishList} from "@/api/dish/dish";
import Cookies from "js-cookie";
import mixinViewModule from "@/mixins/view-module";
import dishContainer from './dish'
import category from "@/views/modules/demo/category";

export default {
  mixins: [mixinViewModule],
  // components: {dishContainer},

  updated() {
    // console.log('菜品信息已更新完成');
  },
  data() {
    return {
      active:false,
      dishesLoading: '',
      setmealDishesLoading: '',
      mixinViewModuleOptions: {
        getDataListURL: '/demo/setmealdish/page',
        getDataListIsPage: true,
      },
      search: false,
      // dishVisible: false,
      dialogVisible: false,
      visible: false,
      url: '',
      num: 0,
      inputValue: '',
      categoryList: [],
      imageUrl: '',
      dishList: [],
      dishTable: [],
      categoryDish: [],
      dishSelection:[],
      dishArray:[],
      dish: {
        categoryName: '',
        name: '',
        status: '',
        price: '',
      },

      dataForm: {
        id: '',
        categoryId: '',
        categoryName: '',
        name: '',
        price: '',
        status: '',
        code: '',
        description: '',
        image: '',
        setmealDishes: [],
      }
    }
  },
  computed: {
    dataRule() {
      return {
        categoryId: [
          {required: true, message: this.$t('validate.required'), trigger: 'blur'}
        ],
        name: [
          {required: true, message: this.$t('validate.required'), trigger: 'blur'}
        ],
        price: [
          {required: true, message: this.$t('validate.required'), trigger: 'blur'}
        ],
        status: [
          {required: true, message: this.$t('validate.required'), trigger: 'blur'}
        ],
        code: [
          {required: true, message: this.$t('validate.required'), trigger: 'blur'}
        ],
        description: [
          {required: true, message: this.$t('validate.required'), trigger: 'blur'}
        ],
        image: [
          {required: true, message: this.$t('validate.required'), trigger: 'blur'}
        ],

      }
    }
  },

  methods: {
    init() {
      this.visible = true
      this.url = `${window.SITE_CONFIG['apiURL']}/sys/oss/upload?token=${Cookies.get('token')}`

      getCategoryList({'type': 2}).then(({data: res}) => {
        if (res.code === 0) {
          this.categoryList = res.data
        } else {
          this.$message.error(res.msg || '操作失败')
        }
      }),
          this.$nextTick(() => {
            this.$refs['dataForm'].resetFields()

            if (this.dataForm.id) {
              this.getInfo()
            } else {
              this.dataForm.setmealDishes = []
              this.imageUrl = ''
            }
          })
    },
    // 获取信息
    getInfo() {
      this.$http.get(`/demo/setmeal/${this.dataForm.id}`).then(({data: res}) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        this.dataForm = {
          ...this.dataForm,
          ...res.data
        }
        this.imageUrl = this.$urlConfig.oosUrl + res.data.image
        this.dataForm.price = String(res.data.price / 100)
        this.dataForm.categoryId = res.data.categoryId

        this.dataForm.setmealDishes = res.data.setmealDishes && res.data.setmealDishes.map(obj => ({
          ...obj,
          value: JSON.parse(obj.value),

        }))


      }).catch(() => {
      })
    },
    // 表单提交
    dataFormSubmitHandle: debounce(function () {
      this.$refs['dataForm'].validate((valid) => {
        if (!valid) {
          return false
        }

        let params = {...this.dataForm}
        params.status=this.dataForm.status?1:0
        params.price*=100

        if(params.setmealDishes!=null&&params.setmealDishes!=''){

        }else{
          this.$message.error('请添加菜品')
          return
        }

        if (!this.imageUrl) {
          this.$message.error('请上传菜品图片')
          return
        }

        this.$http[!this.dataForm.id ? 'post' : 'put']('/demo/setmeal/', params).then(({data: res}) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          this.$message({
            message: this.$t('prompt.success'),
            type: 'success',
            duration: 500,
            onClose: () => {
              this.visible = false
              this.$emit('refreshDataList')
            }
          })
        }).catch(() => {
        })
      })
    }, 1000, {'leading': true, 'trailing': false}),

    // 读取菜品数据
     initDish() {
      //数组去重
       function uniqueFunc(arr,id){
         const res = new Map();
         return arr.filter((item) => !res.has(item.id) && res.set(item.id, 1));
       }
      this.dishArray=[]
      //后端取得所有菜品数据，返回给前端
      this.search=false;
      getDishList().then(({data: res}) => {
        if (res.code === 0) {
          this.dishList = res.data
          let arr=[]
          this.dishList.map(item => {
           arr.push({'id':item.categoryId, 'name':item.categoryName,'active':false})
          })

          this.categoryDish=uniqueFunc(arr,'id')
          if(this.categoryDish!==null){

            setTimeout(() => this.findDish(this.categoryDish[0],0), 100)
          }
          this.dialogVisible = true

        } else {
          this.$message.error(res.msg || '操作失败')
        }
      })

      //默认初始化加载一次，不会判断生命周期 只能延时等页面更新完成
     // if(arr[0][0]!==null){
     //   setTimeout(() => this.findDish(arr[0][0],0), 100)
     // }
    },

    //选中菜品提交
    submitDish() {
      let arr =this.dishArray.map(obj=>{
             let setmealDish = {};
             setmealDish.name=obj.name;
             setmealDish.price=obj.price;
             setmealDish.copies=1;
             setmealDish.dishId=obj.id;
             return setmealDish;

        })
          //去重，防止添加重复菜品
      this.dataForm.setmealDishes.push(...arr)
      let hash = {}
      this.dataForm.setmealDishes=this.dataForm.setmealDishes.reduce((item,setmealDish ) => {
        hash[setmealDish['dishId']] ? '' : hash[setmealDish['dishId']] = true && item.push(setmealDish)
        return item
      }, [])


      console.log(this.dataForm.setmealDishes)
      this.dialogVisible = false
    },
    //退出搜索
    backCategory(){
      this.inputValue=''
      this.initDish()
    },
    //菜品名查找菜品
    searchDish() {
      if (this.inputValue !== null && this.inputValue != '') {
        this.search = true
        this.categoryDish= [],
        this.dishTable=[],
        this.dishList.map(item => {
          //实现中文模糊搜索
          let reg = new RegExp('[\u4E00-\u9FA5]+');//中文匹配正则对象

          if (reg.test(this.inputValue)) {
            //dishTable ：接收搜索后的数据  dishList：查找的数据
            this.dishTable = this.dishList.filter(array => {

              if (array.name != undefined) {
                //匹配输入框的内容
                return array.name.indexOf(this.inputValue) >= 0

              }
              return false

            })

          }

        })
      }

    },


    deleteSetmealDish(val){

     let index = this.dataForm.setmealDishes.findIndex(obj=>{
        return obj.dishId===val;
      })
      if (index>=0){
        this.dataForm.setmealDishes.splice(index,1);
      }

    },

    findDish(item, i) {
      this.dishTable=[]
      this.categoryDish.map(obj=>{
          obj.active=false
      })
      //给数据表赋值
      this.dishList.map(obj => {
        if (obj.categoryId ===item.id) {

          this.dishTable.push(obj)
        }
      })
      item.active=true
    },
    //选中添加的菜品
    dishSelectionChangeHandle(val){
      //扩容数组  val ：子数组 dishSelection： 中间变量 dishArray:最终选择的容器
      this.dishSelection=val
      if (this.dishSelection!=null){
        this.dishSelection.map(item=>{
          if(this.dishArray.includes(item)){
          }else {
            this.dishArray.push(item)
          }
          return item
        })
      }

      // this.dishArray=this.dishArray.concat(this.dishSelection);



    },
    //删除菜品
    deleteDish(i){
      this.dishArray.splice(i, 1)
    },

    // 上传之前
    beforeUploadHandle(file) {
      if (file.type !== 'image/jpg' && file.type !== 'image/jpeg' && file.type !== 'image/png' && file.type !== 'image/gif') {
        this.$message.error(this.$t('upload.tip', {'format': 'jpg、png、gif'}))
        // setTimeout(() => {
        //   this.$refs.upload.clearFiles();
        // }, 100);
        return false
      }
      this.num++
    },
    // 上传成功
    successHandle(res, file) {



      if (res.code !== 0) {
        console.log('hhhhhhh')
        return this.$message.error(res.msg)
      }
      if (this.num === 1) {
        this.imageUrl = res.data.src + res.data.fileName

        this.dataForm.image = res.data.fileName

        this.$message({
          message: this.$t('prompt.success'),
          type: 'success',
          duration: 500,

        })
        this.num--
      }
    },

    onChange(file) {
      if (file) {
        const suffix = file.name.split('.')[1]
        const size = file.size / 1024 / 1024 < 2
        if (['png', 'jpeg', 'jpg'].indexOf(suffix) < 0) {
          this.$message.error('上传图片只支持 png、jpeg、jpg 格式！')
          this.$refs.upload.clearFiles()
          return false
        }
        if (!size) {
          this.$message.error('上传文件大小不能超过 2MB!')
          return false
        }
        return file
      }
    },

  }
}
</script>
<style>
#overflow {
  overflow-y: auto;

}

.btn-box {
  width: 180px;
  display: flex;
  justify-content: space-between;
  float: right;
  margin-bottom: 10px;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 178px;
  height: 178px;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.dishBox {
  /*display: flex;*/
  /*flex-direction: row;*/
  /*width:100% ;*/

}

.dishBox .dishBox-category {
  padding: 15px;
  display: flex;
  flex-direction: column;
  /*width: 30%;*/
  margin-right: 5px;
}

.dishBox .dishBox-category .dishBox-category-item {
  height: 50px;
  text-align: center;
  vertical-align: middle;
  line-height: 50px;
  font-size: 15px;
}

.dishBox .dishBox-category .dishBox-category-newItem {

  position: relative;
  height: 50px;
  text-align: center;
  vertical-align: middle;
  line-height: 50px;
  font-size: 16px;
  color: #409EFF;
}

.dishBox .dishBox-category .dishBox-category-newItem:after {
  content: '';
  position: absolute;
  left: auto;
  bottom: 3px;
  top: 3px;
  right: 0;
  width: 3px;
  background-color: #409EFF;
}

.dishBox .dishBox-dish {
  /*width: 200px;*/
}
.dishBox .dishBox-choose {
  display: flex;
  flex-direction: column;

}
.dishBox .dishBox-choose .el-tag{
  display: flex;
  justify-content: space-between;
  margin-top: 30px;
  margin-left: 100px;
  width: 300px;
  height: 30px;

}
.dishBox .dishBox-choose .el-tag span{
  text-align: center;
  line-height: 30px;
  font-size: 15px;

  color: #ff4d51;
  font-family:楷体;
}
.dish-btn {
  margin-left: 20px;
}
</style>